<?php
// Autor (c) Miroslav Novak, www.platiti.cz
// Pouzivani bez souhlasu autora neni povoleno
// #Ver:PRV043#


require_once(DIR_APPLICATION."../UniModul/UniModul.php");

class ControllerPaymentUniAdapter extends Controller {

	protected $uniModul;
	protected $lowCaseBinderName;

	public function __construct($registry, $uniModulName = null, $subMethod='') {
		BeginUniErr();
		parent::__construct($registry);
		$this->lowCaseBinderName = strtolower($uniModulName).'binder'.strtolower($subMethod);
		$uniFact = new UniModulFactory();
		$configInfo = $uniFact->getConfigInfo($uniModulName, null, $subMethod);
		$this->configSetting = $this->getConfigData($configInfo, $uniModulName);
		$this->uniModul = $uniFact->createUniModul($uniModulName, $this->configSetting, $subMethod);
		EndUniErr();
	}

	function getConfigData($configInfo, $uniModulName) {
		$configData = array();
		foreach ($configInfo->configFields as $configField) {
			$baseBinder = strtolower($uniModulName).'binder';  // bez submetod
			$configData[$configField->name] = $this->config->get($baseBinder.'_'.$configField->name);
		}

		$uniModulConfig = new UniModulConfig();
		$uniModulConfig->mysql_server = DB_HOSTNAME;
		$uniModulConfig->mysql_dbname = DB_DATABASE;
		$uniModulConfig->mysql_login = DB_USERNAME;
		$uniModulConfig->mysql_password = DB_PASSWORD;
		//DB_PREFIX ..
		if (DB_DRIVER != 'mysql') user_error('Eshop pouziva jinou nez mysql databazi');
		$cfgs = create_initialize_object('ConfigSetting', array('configData'=>$configData, 'uniModulConfig'=>$uniModulConfig));
		return $cfgs;
	}


	protected function index() {
		BeginUniErr();
		$this->language->load('payment/uniadapter');
    	//$this->data['text_brand'] = $this->language->get('text_brand');

		$this->data['button_confirm'] = $this->language->get('button_confirm');
		$this->data['button_back'] = $this->language->get('button_back');

		$this->data['action'] = HTTPS_SERVER . 'index.php?route=payment/'.$this->lowCaseBinderName.'/postback';
		if ($this->request->get['route'] != 'checkout/guest_step_3') {
			$this->data['back'] = HTTPS_SERVER . 'index.php?route=checkout/payment';
		} else {
			$this->data['back'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_2';
		}
		
		if (isset($this->uniModul)) { //vopruz kvuli adapteru
			$orderToPayInfo = $this->getOrderToPayInfo();
			$prePayGWInfo = $this->uniModul->queryPrePayGWInfo($orderToPayInfo);
			$this->data['selectCsPayBrand'] = $prePayGWInfo->selectCsPayBrand;
			$this->data['selectCsPayBrandTitle'] = $prePayGWInfo->selectCsPayBrandTitle;
			$this->data['forexMessage'] = $prePayGWInfo->forexMessage;
			$this->data['minilogo'] = "<span style=\"background:url('http://www.platiti.cz/muzo/minilogo.png')\"></span>";
		}
		
		//$this->load->model('checkout/order');   //uz se vola v getOrderToPayInfo
	
		$this->id = 'payment';

		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/uniadapter.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/payment/uniadapter.tpl';
		} else {
			$this->template = 'default/template/payment/uniadapter.tpl';
		}	
		
		$this->render();	
		EndUniErr();
	}

	public function getPrePayGWInfoForModel() {
		//var_dump($this->session->data); wwww();
		
		//session->data[order_id] jeste v tuto chvily neexistuje, takze orderInfo z controlleru nelze pouzit
		//$orderToPayInfo = $this->getOrderToPayInfo();
		
		$orderToPayInfo = new OrderToPayInfo();
		$orderToPayInfo->language = $this->session->data['language'];
		$orderToPayInfo->currency = $this->session->data['currency'];
		$orderToPayInfo->currencyRates = $this->getCurrencyRates();
		$prePayGWInfo = $this->uniModul->queryPrePayGWInfo($orderToPayInfo);
		return $prePayGWInfo;
	}
	
	protected function getCurrencyRates() {
		$curobj = $this->registry->get('currency');
		$curarr = (array) $curobj;
		$currencies = $curarr["\0Currency\0currencies"];
		$currencyRates = array();
		foreach ($currencies as $code=>$cur) {
			$currencyRates[$code] = $cur['value'];
		}
		return $currencyRates;
	}
	
	protected function getOrderToPayInfo() {
		$this->load->model('checkout/order');
		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

		$ver14 = strpos('v'.VERSION, 'v1.4')!==false;
		if ($ver14) {
			$currency = $order_info['currency'];
			$value = $order_info['value'];
		} else {
			$currency = $order_info['currency_code'];
			$value = $order_info['currency_value'];
		}
		$order_total = $this->currency->format($order_info['total'], $currency, $value, FALSE);

		
		$orderToPayInfo = new OrderToPayInfo();
		$orderToPayInfo->shopOrderNumber = $this->session->data['order_id'];
		$orderToPayInfo->shopPairingInfo = $this->session->data['order_id'];
		$orderToPayInfo->amount = $order_total;
		$orderToPayInfo->currency = $currency;
		if (isset($_REQUEST['brand'])) {
			$orderToPayInfo->ccBrand = $_REQUEST['brand'];
		}
		
		
		$customerData = new CustomerData();
		$customerData->first_name = $order_info['firstname'];
		$customerData->last_name = $order_info['lastname'];
		$customerData->email = $order_info['email'];
		$customerData->street = $order_info['payment_address_1'].' '.$order_info['payment_address_2'];
		$customerData->city = $order_info['payment_city'];
		$customerData->post_code = $order_info['payment_city'];
		$customerData->country = $order_info['payment_country'];
		$customerData->phone = $order_info['telephone'];
		$orderToPayInfo->customerData = $customerData;

		$orderToPayInfo->language = $this->registry->get('config')->get('config_language');
		$orderToPayInfo->description = $this->config->get('config_name');

		$replyUrl = $replyUrl = HTTPS_SERVER . 'index.php?route=payment/'.$this->lowCaseBinderName.'/callback';
		$orderToPayInfo->replyUrl = $replyUrl;

		$replyUrl = $replyUrl = HTTPS_SERVER . 'index.php?route=payment/'.$this->lowCaseBinderName.'/notify';
		$orderToPayInfo->notifyUrl = $replyUrl;

		$orderToPayInfo->currencyRates = $this->getCurrencyRates();
		
		
		return $orderToPayInfo;
	}
	
	public function postback() {
		BeginUniErr();
		$orderToPayInfo = $this->getOrderToPayInfo();

		$redirectAction = $this->uniModul->gatewayOrderRedirectAction($orderToPayInfo);
		if ($redirectAction->orderReplyStatus != null) {   // okamzita odpoved muze byt i zaroven s redirektem - napr. Cetelem
			$frontend_redir = $redirectAction->redirectUrl==null && $redirectAction->redirectForm==null;
			var_dump($redirectAction);
			$this->processReply($redirectAction->orderReplyStatus, $frontend_redir);
		}
		if ($redirectAction->redirectUrl != null) {
			ResetUniErr();
			$this->redirect($redirectAction->redirectUrl);
		} else if ($redirectAction->redirectForm != null) {
			$this->uniModul->formRedirect($redirectAction->redirectForm);
		}
		EndUniErr();
	}

	public function callback() {
		BeginUniErr();
		$language = $this->registry->get('config')->get('config_language');
		$orderReplyStatus = $this->uniModul->gatewayReceiveReply($language);
		$this->processReply($orderReplyStatus, true);
		EndUniErr();
	}

	public function notify() {
		BeginUniErr();
		$orderReplyStatus = $this->uniModul->gatewayReceiveNotification();
		$this->processReply($orderReplyStatus, false);
		EndUniErr();
	}
	
	public function processReply($orderReplyStatus, $frontend_redir) {
		$cfg = $this->configSetting->configData;
		switch ($orderReplyStatus->orderStatus) {
			case OrderStatus::$successful:
				$newState = $cfg['orderStatusSuccessfull'];
				$guiOk = true;
				break;
			case OrderStatus::$pending:
				$newState = $cfg['orderStatusPending'];
				$guiOk = true;
				break;
			case OrderStatus::$failedFinal:
				$newState = $cfg['orderStatusFailed'];
				$guiOk = false;
				break;
			case OrderStatus::$failedRetriable;
			case OrderStatus::$invalidReply;
				$newState = null;
				$guiOk = false;
			default:
		}

		BeginSynchronized();

		$order_id = $orderReplyStatus->shopPairingInfo;
		$this->load->model('checkout/order');
		$order_info = $this->model_checkout_order->getOrder($order_id);
		if ($newState != null) {

			$comment = $order_info['comment'];
			if ($comment != '') {
				$comment .= "\n\n";
			}
			//$comment .= 'UniAdapter gwOrdnum ='.$orderReplyStatus->gwOrderNumber;
			$language = $this->registry->get('config')->get('config_language');  // je to potreba i nize, notifikace nevadi
			$comment .= $this->uniModul->dictionary->get('orderDetailGwOrdNum', $language).': '.$orderReplyStatus->gwOrderNumber;
			if ($orderReplyStatus->forexNote !== null) {
				$comment .= "<br/>".$this->uniModul->dictionary->get('forexNoteLabel', $language). ': ' . $orderReplyStatus->forexNote;
			}
			
			if ($order_info['order_status_id'] == 0) {
				$this->model_checkout_order->confirm($order_id, $newState, $comment, TRUE);
			} else {
				if ($order_info['order_status_id'] != $newState) {
					$this->model_checkout_order->update($order_id, $newState, $comment, TRUE);
				}
			}
		}
		
		EndSynchronized();
		
		if ($frontend_redir) {
			if ($guiOk) {
				ResetUniErr();
				$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/success');
			} else {
				$this->language->load('payment/uniadapter');
				$errMsg = $this->language->get('message_failure');
				if ($orderReplyStatus->resultText != null) {
					$errMsg .= '<br/>'.$orderReplyStatus->resultText;
				}
				$this->session->data['error'] = $errMsg;
				
				$ver14 = strpos('v'.VERSION, 'v1.4')!==false;
				if ($ver14) {
					ResetUniErr();
					$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/payment');
				} else {
					//$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/checkout');  // nezobrazuje error hlasku v 1.5
					////$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/cart');    // zobrazuje error hlasku v 1.5.1 ale ne v 1.5.3
					$this->showFailurePage($errMsg);
				}
				
			}
		}
	
	}

	private function showFailurePage($errMsg) {

			$this->data['error_warning'] = $errMsg;
			$this->data['continue_text'] = $this->language->get('button_continue');
			$this->data['continue_url'] = $this->url->link('checkout/checkout');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/uniadapter_failure.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/payment/uniadapter_failure.tpl';
			} else {
				$this->template = 'default/template/payment/uniadapter_failure.tpl';
			}

			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);

			$this->response->setOutput($this->render());
	
	}

	
	
}
